//
//  BSSAddPhotosCollectionViewController.m
//  BrightSunnySky
//
//  Created by 传铎 on 2020/9/17.
//  Copyright © 2020 PURANG. All rights reserved.
//

#import "BSSAddPhotosCollectionViewController.h"
#import "TZImagePickerController.h"
#import <AssetsLibrary/ALAsset.h>
#import<AssetsLibrary/AssetsLibrary.h>
#import <AVFoundation/AVCaptureDevice.h>
#import "BSSUploadImagApi.h"

#import "BSSAddPhotosCollectionViewCell.h"
#import "BSSMessageBoardPhotosCollectionViewCell.h"


@interface BSSAddPhotosCollectionViewController ()<UICollectionViewDataSource,UICollectionViewDelegate,UINavigationControllerDelegate,UIImagePickerControllerDelegate,UIActionSheetDelegate,UICollectionViewDelegateFlowLayout,TZImagePickerControllerDelegate>
@property (nonatomic,strong) NSMutableArray * photoArray;
@end

@implementation BSSAddPhotosCollectionViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    self.view.backgroundColor = colorCode(@"f2f2f2");
    _photoArray = [NSMutableArray array];
    _deleArr = [NSMutableArray array];
    if (!IsEmpty(_pictureArray)) {
        [_photoArray addObjectsFromArray:_pictureArray];
    }
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc]init];
    layout.itemSize = CGSizeMake(90, 100);
    layout.minimumInteritemSpacing = 5;
    if(!_isHorizontal){
        layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    }else{
        layout.scrollDirection = UICollectionViewScrollDirectionVertical;
    }
//    layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;//UICollectionViewScrollDirectionVertical;
    layout.minimumLineSpacing = 5; //上下的间距 可以设置0看下效果
    layout.sectionInset = UIEdgeInsetsMake(5.f, 5, 5.f, 5);
    UIView*diView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 15, 100)];
    [self.view addSubview:diView];
    diView.backgroundColor = colorCode(@"ffffff"); 
    //创建 UICollectionView
    self.pictureCollectonView = [[UICollectionView alloc] initWithFrame:CGRectMake(15, 0, self.view.frame.size.width - 15, 100 )collectionViewLayout:layout];
    _pictureCollectonView.showsHorizontalScrollIndicator = NO;
    _pictureCollectonView.showsVerticalScrollIndicator = NO;
    [self.pictureCollectonView registerClass:[BSSMessageBoardPhotosCollectionViewCell class]forCellWithReuseIdentifier:@"cell"];
    [self.pictureCollectonView registerClass:[BSSAddPhotosCollectionViewCell class]forCellWithReuseIdentifier:@"cell1"];
    self.pictureCollectonView.backgroundColor = [UIColor whiteColor];
    self.pictureCollectonView.delegate = self;
    self.pictureCollectonView.dataSource = self;
    [self.view addSubview:self.pictureCollectonView];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(adds:) name:@"addPhotos" object:nil];
    
}

- (void)imagePickerController:(TZImagePickerController *)picker didFinishPickingPhotos:(NSArray<UIImage *> *)photos sourceAssets:(NSArray *)assets{
    [self postImage:photos];
}
- (void)adds:(NSNotification *)not{
    UIImage *image = not.object;
    [self postImage:@[image]];
}

- (void)postImage:(NSArray *)sender{
    if(IsEmpty(sender)){
        [MBProgressHUD showText:@"获取图片失败"];
        return;
    }
    BSSUploadImagApi *api  = [[BSSUploadImagApi alloc]initWithURL:@"" dic:@{} imageArray:sender];
    api.isFiles = YES;
    [api startRequest:^(BSSRequestStatus requestStatus, NSString *message, id responseObject) {
        
        [MBProgressHUD hideHUD];
        if (requestStatus == BSSRequestStatusSuccess) {
            
            if (!IsEmpty(responseObject[@"data"])) {
                
                for (NSDictionary *dict in responseObject[@"data"]) {
                    [self.photoArray addObject:dict[@"imageURL"]];
                }
                [self.pictureCollectonView reloadData];
                if (self.chooseMessageBoardPicture) {
                    self.chooseMessageBoardPicture(self.photoArray,_deleArr);
                }
            }
            
        }else{
            
            [MBProgressHUD showText:message];
        }
    }];
}
#pragma mark - collectionView 调用方法
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.photoArray.count + 1;
}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row == 0) {
        static NSString *addItem = @"cell";
        BSSMessageBoardPhotosCollectionViewCell *addItemCell = [collectionView dequeueReusableCellWithReuseIdentifier:addItem forIndexPath:indexPath];
        addItemCell.backgroundImageV.image = [UIImage imageNamed:@"BSSMessageBoard_addPhoto"];
        return addItemCell;
    }else{
        static NSString *identify = @"cell1";
        BSSAddPhotosCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:identify forIndexPath:indexPath];
        [cell.deleImageBnt addTarget:self action:@selector(deleImageClick:) forControlEvents:UIControlEventTouchUpInside];
        cell.deleImageBnt.tag = 999 + indexPath.row;
        [cell.imageView sd_setImageWithURL:[NSURL URLWithString:self.photoArray[indexPath.row - 1]] placeholderImage:[UIImage imageNamed:@"no_photo"]];
        return cell;
    }
    
    
}
- (void)deleImageClick:(UIButton *)sender{
    NSInteger index = sender.tag - 1000;
    [_deleArr addObject:self.photoArray[index]];
    [self.photoArray removeObjectAtIndex:index];
    [self.pictureCollectonView reloadData];
    if (self.chooseMessageBoardPicture) {
        self.chooseMessageBoardPicture(self.photoArray,self.deleArr);
    }
}
//用代理
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    
    if (self.photoArray.count == 0) {
        if (self.photoArray.count == 5) {
            [MBProgressHUD showText:@"最多可以上传5张图片"];
            return;
        }
        NSArray *arr = @[@"拍照",@"从相册选择"];
        WEAKSELF
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle: UIAlertControllerStyleActionSheet];
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
        for (int i = 0; i < arr.count; i++) {
            UIAlertAction *archiveAction1 = [UIAlertAction actionWithTitle:arr[i] style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                if (i == 0) {
                    [weakSelf camerachooseMessageBoardPicture];
                }else{
                    [weakSelf photoAlbumchooseMessageBoardPicture];
                }
            }];
            [alertController addAction:archiveAction1];
        }
        
        [alertController addAction:cancelAction];
        alertController.modalPresentationStyle = UIModalPresentationFullScreen;
    [self presentViewController:alertController animated:YES completion:nil];
        
    }else{
       
    }
}
- (void)camerachooseMessageBoardPicture{
    
    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    
    if (authStatus == AVAuthorizationStatusRestricted || authStatus ==AVAuthorizationStatusDenied)
        
    {
        if ([[[UIDevice currentDevice] systemVersion] floatValue] > 10.1) {
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"您的相机权限还未开启" message:@"请到设置-隐私-相机-应用中开启" preferredStyle:UIAlertControllerStyleAlert];
            
            [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
                
            }]];
            alert.modalPresentationStyle = UIModalPresentationFullScreen;
            [self presentViewController:alert animated:YES completion:nil];
            return;
        }else{
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"您的相机权限还未开启,是否开启" preferredStyle:UIAlertControllerStyleAlert];
            
            [alert addAction:[UIAlertAction actionWithTitle:@"开启" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
                [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
            }]];
            
            [alert addAction:[UIAlertAction actionWithTitle:@"下次再说" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                
            }]];
            alert.modalPresentationStyle = UIModalPresentationFullScreen;
            [self presentViewController:alert animated:YES completion:nil];
            return;
            
        }
    }
    //相机
}
- (void)photoAlbumchooseMessageBoardPicture{
    ALAuthorizationStatus author = [ALAssetsLibrary authorizationStatus];
    
    if(author == ALAuthorizationStatusRestricted || author ==ALAuthorizationStatusDenied){
  
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"您未允许使用相册功能，是否开启" message:@"请到设置-隐私-相册-应用中开启" preferredStyle:UIAlertControllerStyleAlert];
        
        [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            
        }]];
        alert.modalPresentationStyle = UIModalPresentationFullScreen;
    [self presentViewController:alert animated:YES completion:nil];
        return;
        
    }
    TZImagePickerController *vc = [[TZImagePickerController alloc] initWithMaxImagesCount:10 delegate:self];
    vc.maxImagesCount = MIN(5-self.photoArray.count, 5);
    vc.navigationBar.barTintColor = [UIColor blackColor];
    vc.oKButtonTitleColorDisabled = [UIColor lightGrayColor];
    vc.oKButtonTitleColorNormal = [UIColor greenColor];
    vc.allowPickingVideo = NO;
    vc.allowPickingOriginalPhoto = NO;
    vc.modalPresentationStyle = UIModalPresentationFullScreen;
                vc.modalPresentationStyle = UIModalPresentationFullScreen;
                [self presentViewController:vc animated:YES completion:nil];
}
-(NSString *)UIImageToBase64Str:(UIImage *) image{
    NSData *data = UIImageJPEGRepresentation(image, 0.6f);
    NSString *encodedImageStr = [data base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
    return encodedImageStr;
}

#pragma mark -XLImageViewerDelegate
- (void)clickDeletedButtonIndex:(NSInteger)index{
    [_deleArr addObject:self.photoArray[index]];
    [self.photoArray removeObjectAtIndex:index];
    [self.pictureCollectonView reloadData];
    if (self.chooseMessageBoardPicture) {
        self.chooseMessageBoardPicture(self.photoArray,self.deleArr);
    }
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
